//
//  ILFashionViewController.m
//  ILife
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILFashionViewController.h"
#import "ILSelectionTableViewCell.h"
#import "ILHomePageModel.h"
#import <AFHTTPRequestOperationManager.h>
#import <MJRefresh.h>
#import "ILFashionMoreTableViewCell.h"
#import "ILFashionWebViewController.h"
#import "ILFashionListViewController.h"
#import "FMDatabase.h"
#import <SDWebImage/SDImageCache.h>
#import "ILClearCachFile.h"
@interface ILFashionViewController ()<UITableViewDelegate,UITableViewDataSource>



@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) UITableView *moreTableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) NSMutableArray *moreSourceArray;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableSet *indexSet;
@property(nonatomic,strong)FMDatabase *dataBase;//数据库

@property (nonatomic, assign) BOOL isHidden;

@end

@implementation ILFashionViewController

-(NSMutableSet *)indexSet
{
    if (_indexSet == nil) {
        self.indexSet = [NSMutableSet setWithCapacity:0];
    }
    return _indexSet;
}



- (NSMutableArray *)moreSourceArray
{
    if (_moreSourceArray == nil) {
        self.moreSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _moreSourceArray;
}


- (NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil) {
        self.dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor= [UIColor blackColor];
    
    self.navigationItem.title = @"爱时尚";

    self.isHidden = NO;
    
    
    
// 创建数据库
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"ILive.db"];

    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        // 创建表格
        
        [_dataBase executeUpdate:@"create table fashion(thumb text, title text, cat_title text, time text, descp text)"];
        
        [_dataBase executeUpdate:@"create table fashionMore(cat_title text, english_title text)"];
        
        
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSetFashion = [_dataBase executeQueryWithFormat:@"select * from fashion"];
    FMResultSet *resultSetMore = [_dataBase executeQueryWithFormat:@"select * from fashionMore"];
    
    while ([resultSetFashion next]) {
        NSString *thumb = [resultSetFashion stringForColumn:@"thumb"];
        NSString *title = [resultSetFashion stringForColumn:@"title"];
        NSString *cat_title = [resultSetFashion stringForColumn:@"cat_title"];
        NSString *time = [resultSetFashion stringForColumn:@"time"];
        NSString *descp = [resultSetFashion stringForColumn:@"descp"];
        
        ILHomePageModel *homeModel = [[ILHomePageModel alloc]init];
        homeModel.thumb = thumb;
        homeModel.title = title;
        homeModel.cat_title = cat_title;
        homeModel.published = time;
        homeModel.descrip = descp;
        [self.dataSourceArray addObject:homeModel];
    }
    [resultSetFashion close];
    
    
    while ([resultSetMore next]) {
        NSString *title = [resultSetMore stringForColumn:@"cat_title"];
        NSString *english = [resultSetMore stringForColumn:@"english_title"];
        
        ILFashionMoreModel *moreModel = [[ILFashionMoreModel alloc]init];
        moreModel.cat_title = title;
        moreModel.english_title = english;
        [self.moreSourceArray addObject:moreModel];
    }
    [resultSetMore close];
    
    
    
    
    
// 添加更多按钮

    UIButton *leftButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    leftButton.frame = CGRectMake(20, 20, 30, 30);
    [leftButton setImage:[UIImage imageNamed:@"more"] forState:(UIControlStateNormal)];
    [leftButton addTarget:self action:@selector(showMore:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem* leftBtnItem = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    [self.navigationItem setLeftBarButtonItem:leftBtnItem];
    
    
    self.pageNum = 1;
    
    [self reloadMainTableView];
    [self.view addSubview:_mainTableView];
    [self requestData];
    
    
    [self reloadMoreTableView];
    [self.view addSubview:_moreTableView];
    [self requestMoreData];
    

// 回到顶部按钮
    UIButton *topButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [topButton setImage:[UIImage imageNamed:@"top"] forState:(UIControlStateNormal)];
    topButton.frame = CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 100, 40, 40);
    topButton.backgroundColor = [UIColor grayColor];
    topButton.alpha = 0.5;
    topButton.layer.cornerRadius = 20;
    topButton.layer.masksToBounds = YES;
    [topButton addTarget:self action:@selector(toTop) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:topButton];
    
    
    
// 取消分割线
    self.mainTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
// 下拉刷新
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    }];
    
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeader)];
    
    
// 上提加载
    self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFooter)];
    [self.mainTableView.footer beginRefreshing];
    
    
    
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(showMoreLeft)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];
    
    
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(showMoreRight)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeRight];
    
    
}





// 添加手势 
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(showMoreLeft)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];
    
    
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(showMoreRight)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeRight];
    
    
    
}


// 返回顶部
- (void)toTop
{
    [self.mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
}


// 手势向右
- (void)showMoreRight
{
    if (self.isHidden == NO) {
        self.isHidden = YES;
        
        [self showRight];
    }
}

// 手势向左
- (void)showMoreLeft
{
    if (self.isHidden == YES) {
        self.isHidden = NO;
        
        [self showLeft];
    }
}

// 向左隐藏
- (void)showLeft
{
    [UIView animateWithDuration:0.2 animations:^{
        _moreTableView.frame = CGRectMake( -SCREEN_WIDTH*0.5, 64, SCREEN_WIDTH*0.5, SCREEN_HEIGHT-112);
    }];
    self.mainTableView.userInteractionEnabled = YES;
}

// 向右出现
- (void)showRight
{
    [UIView animateWithDuration:0.2 animations:^{
        _moreTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH*0.5, SCREEN_HEIGHT-112);
    }];
    
    self.mainTableView.userInteractionEnabled = NO;
}


// 点击Button
- (void)showMore:(UIButton *)sender
{
    
    if (self.isHidden == NO) {
        self.isHidden = YES;
        [self showRight];
    }
    else
    {
        self.isHidden = NO;
        [self showLeft];
    }

}


// 刷新头
- (void)refreshHeader
{
    
    self.pageNum = 1;
    [self requestData];
}

// 刷新尾
- (void)refreshFooter
{
    self.pageNum +=1;
    [self requestData];
}



- (void)reloadMainTableView
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:(UITableViewStylePlain)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [_mainTableView registerClass:[ILSelectionTableViewCell class] forCellReuseIdentifier:@"aa"];
    
}

- (void)reloadMoreTableView
{
    
    _moreTableView = [[UITableView alloc]initWithFrame:CGRectMake(-SCREEN_WIDTH*0.5, 64, SCREEN_WIDTH*0.5, SCREEN_HEIGHT - 112) style:(UITableViewStylePlain)];
    _moreTableView.delegate = self;
    _moreTableView.dataSource = self;
    [_moreTableView registerClass:[ILFashionMoreTableViewCell class] forCellReuseIdentifier:@"more"];
    _moreTableView.tableFooterView = [[UIView alloc]init];
    
}



- (void)requestMoreData
{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    // AFNetWork2.0以上要添加下面的话
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型

    [manger GET:@"http://app.ellemen.com/?app=rss&controller=elleplus&action=elleplus_getcatlist" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        // 在请求数据之前删除之前的数据 以免数据出现重叠
        [_dataBase executeUpdate:@"delete from fashionMore"];
        
        [self.moreSourceArray removeAllObjects];
        
        for (NSDictionary *dic in responseObject[@"data"]) {
            ILFashionMoreModel *moreModel = [[ILFashionMoreModel alloc]init];
            [moreModel setValuesForKeysWithDictionary:dic];
            [self.moreSourceArray addObject:moreModel];
            
            [_dataBase executeUpdate:@"insert into fashionMore (cat_title, english_title) values(?,?)",moreModel.cat_title,moreModel.english_title];
            
        }
        
        [self.moreTableView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"error %@",error);
    }];
    
}



- (void)requestData
{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    // AFNetWork2.0以上要添加下面的话
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    
    NSString *str = @"http://app.ellemen.com/?app=rss&controller=elleplus&action=elleplus_homelist&num=10&pagenum=";
    NSString *urlStr = [str stringByAppendingString:[NSString stringWithFormat:@"%ld",(long)self.pageNum]];
    // 在请求数据之前删除之前的数据 以免数据出现重叠
    [_dataBase executeUpdate:@"delete from fashion"];
    
    [manger GET:urlStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        if (self.pageNum == 1) {
            [self.dataSourceArray removeAllObjects];
        }
        
        for (NSDictionary *dic in responseObject[@"data"]) {
            ILHomePageModel *homeModel = [[ILHomePageModel alloc]init];
            [homeModel setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:homeModel];
            
            [_dataBase executeUpdate:@"insert into fashion(thumb, title, cat_title, time, descp) values(?,?,?,?,?)",homeModel.thumb,homeModel.title,homeModel.cat_title,homeModel.published,homeModel.descrip];
            
        }
    
        
        // 停止刷新
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];
        [self.mainTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"请求失败 %@",error);
        [self.mainTableView.header endRefreshing];
        [self.mainTableView.footer endRefreshing];

    }];
}



#pragma make UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _mainTableView) {
        return _dataSourceArray.count;
    }
    else
    {
        return _moreSourceArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == _mainTableView ) {
        ILSelectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aa" forIndexPath:indexPath];
        
        
        cell.configuer = _dataSourceArray[indexPath.row];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else
    {
        ILFashionMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"more" forIndexPath:indexPath];
        cell.configuer = _moreSourceArray[indexPath.row];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _mainTableView) {
        return SCREEN_WIDTH + 40;
    }
    else
    {
        return SCREEN_HEIGHT*0.1-8;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _mainTableView) {
        ILFashionWebViewController *webVC = [[ILFashionWebViewController alloc]init];
        
        webVC.webUrl =((ILHomePageModel *) _dataSourceArray[indexPath.row]).url;
        webVC.contentid = ((ILHomePageModel *) _dataSourceArray[indexPath.row]).contentid;
        webVC.home_contentid = ((ILHomePageModel *) _dataSourceArray[indexPath.row]).home_contentid;
        webVC.from = @"1";
        
        [self.navigationController pushViewController:webVC animated:YES];
        
        
    }
    else
    {
        ILFashionListViewController *listVC = [[ILFashionListViewController alloc]init];
        
        listVC.catid = ((ILFashionMoreModel *)_moreSourceArray[indexPath.row]).catid;
        
        [self.navigationController pushViewController:listVC animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}










/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
